import pymysql


# 数据库工具封装
class Database_Tool:
    @staticmethod
    def __db_connect():
        conn = pymysql.connect(host="211.103.136.244", port=7061, user="student", password="iHRM_student_2022",
                               database="ihrm", charset="utf8")
        return conn

    @staticmethod
    def query_one(sql):
        my_conn = None
        my_cursor = None
        res = None
        try:
            my_conn = Database_Tool.__db_connect()
            my_cursor = my_conn.cursor()
            my_cursor.execute(sql)
            res = my_cursor.fetchone()
        except Exception as e:
            print("执行sql语句错误", str(e))
            raise
        finally:
            my_cursor.close()
            my_conn.close()
            return res
    #增加修改删除
    @staticmethod
    def uid(sql):
        my_conn=None
        my_cursor=None
        try:
            #连接数据库
            my_conn = Database_Tool.__db_connect()
            #创建游标
            my_cursor = my_conn.cursor()
            #执行sql语句并且记录影响了多少行
            raw = my_cursor.execute(sql)
            print("增删改影响了多少行", raw)
            #执行需要提交
            my_conn.commit()
        except Exception as e:
            #发生错误需要进行回滚(停止)
            my_conn.rollback()
            print("增删改语句执行错误",e)
            raise
        finally:
            #关闭游标
            my_cursor.close()
            #关闭连接
            my_conn.close()


if __name__ == '__main__':
    db = Database_Tool()
    ret = db.query_one("SELECT *FROM bs_user WHERE id='1239645'")
    db.uid("DELETE FROM bs_user WHERE mobile='13021458548';")
    db.uid("DELETE FROM bs_user WHERE mobile='15237213726';")
